package com.chzc.fm.duotin.ui.home;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chzc.fm.duotin.R;
import com.chzc.fm.duotin.adapter.viewpager.HomeMyPagerAdapter2;
import com.chzc.fm.duotin.bean.home.PlayList2Data;
import com.chzc.fm.duotin.event.PlayListEvent;
import com.chzc.fm.duotin.ui.home.utils.FragmentPlayList2;
import com.chzc.fm.duotin.ui.home.utils.HomeUtils;
import com.chzc.fm.duotin.utils.DuotinTask;
import com.chzc.fm.duotin.utils.FastBlur;
import com.chzc.fm.duotin.utils.FileUtils;
import com.chzc.fm.duotin.utils.HttpUtil;
import com.chzc.fm.duotin.utils.ImageUtil;
import com.chzc.fm.duotin.utils.LogUtil;
import com.chzc.fm.duotin.utils.Unicode2CN;
import com.lzy.widget.PullZoomView;
import com.lzy.widget.PullZoomView.OnScrollListener;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;



public class PullListViewActivity2 extends AppCompatActivity implements AdapterView.OnItemClickListener  {

    private ViewPager viewPager;
  // LayoutInflater inflater;
    private ImageView ivBackground;
    private TextView tvBtnAllPlayList,tvBtnDownLoad,tvBtnAllPlayLists,tvBtnDownLoads;//下载，全部节目
    private ImageView ivDot1,ivDot2;
    //存储小圆点
    private List<ImageView> mIvDotList=new ArrayList<>();
    //标题栏
    private TextView tvTitle;
    private ImageView ivBack;
    //升序与排序
    private ImageView ivSort;
    //全部节目的数据
    private List<PlayList2Data.ContentListBean.DataListBean> dataList;

    private PullZoomView pullZoomView;
    //浮动框停留效果
    private RelativeLayout llroot;

    private RelativeLayout rlTop;

    private RelativeLayout rlMiddle;
    private PullZoomView pzv;
    private View inHeader;

    private float height;//头部的原始高度
    int i = 0;

    private ViewGroup.MarginLayoutParams headerParams;
    private int heights;
    private int currHeight;
    //标题栏中的控件

    private LinearLayout llactionbars;

    //个人信息显示栏
    private ImageView ivHeaderCircle;
    private TextView tvMsgHeader;
    private boolean isAes;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pull_listview_2);

        initView();
        initEvent();
        initData();
        Intent intent = getIntent();
        String needAddId = intent.getStringExtra("urlID");
        //获取数据
        HomeUtils.getDownLoadList(new DuotinTask.IRequestCallback() {
            @Override
            public void success(Object object) {
                //将GBK格式转换为unicode
                String orignData = Unicode2CN.unicode2GBK(object.toString());
                try {
                    JSONObject root = new JSONObject(orignData);
                    String message = root.getString("error_msg");
                    if ("SUCCESS".equals(message)) {
                        final JSONObject data = root.getJSONObject("data");
                        //获取到整个的json格式数据
                        final PlayList2Data playList = PlayList2Data.objectFromData(data.toString());
                        //设置背景图片
                        String imgBurl = playList.getAlbum().getImage_url();
                        setBackgroundPicture(imgBurl);
                        //设置内容
                        final HomeMyPagerAdapter2 vpAdapter = new HomeMyPagerAdapter2(PullListViewActivity2.this,playList);
                        viewPager.setAdapter(vpAdapter);

                        //设置播放页面的数据
                        dataList = playList.getContent_list().getData_list();
                        tvBtnAllPlayList.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Toast.makeText(PullListViewActivity2.this, "点击了那个", Toast.LENGTH_SHORT).show();
                                FragmentManager manager = getSupportFragmentManager();
                                FragmentTransaction transaction = manager.beginTransaction();
                                transaction.replace(R.id.fragment_container,new FragmentPlayList2(dataList)).commit();
                            }
                        });

                        //标题栏文字
                        tvTitle.setText(playList.getAlbum().getTitle());


                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void error(String msg) {

            }
        },needAddId);
        boolean isZoomEnable = intent.getBooleanExtra("isZoomEnable", true);

        pzv.setIsParallax(false);
        pzv.setIsZoomEnable(isZoomEnable);
        pzv.setSensitive(1.5f);
        pzv.setZoomTime(500);

    }

    private void setBackgroundPicture(final String imgBurl) {

        new DuotinTask(new DuotinTask.IRequest() {
            @Override
            public Object doRequest() {

               File file = HttpUtil.download(imgBurl, FileUtils.DIR_IMAGE,FileUtils.getFileNameByHashCode(imgBurl),null);

                return file;
            }
        }, new DuotinTask.IRequestCallback() {
            @Override
            public void success(Object object) {
                //设置模糊背景图片
                File file  = (File) object;
                Bitmap background = BitmapFactory.decodeFile(file.getAbsolutePath());
                FastBlur.blur(PullListViewActivity2.this,background,ivBackground);
            }

            @Override
            public void error(String msg) {

            }
        }).execute();

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Toast.makeText(this, "点击了" + position, Toast.LENGTH_SHORT).show();
    }

    private void initView(){

        //设置内容的viewPager
        //设置头部的布局
        viewPager = (ViewPager) findViewById(R.id.vpTop);
        //绑定背景
        ivBackground = (ImageView) findViewById(R.id.ivBackground);
        //滚动小圆点
        ivDot1 = (ImageView) findViewById(R.id.iv_dot1);
        ivDot2 = (ImageView) findViewById(R.id.iv_dot2);
        mIvDotList.add(ivDot1);
        mIvDotList.add(ivDot2);
        //标题栏
        tvTitle = (TextView) findViewById(R.id.tv_title);
        ivBack = (ImageView) findViewById(R.id.iv_back);

        pzv = (PullZoomView) findViewById(R.id.pzv);

        llactionbars = (LinearLayout)findViewById(R.id.ll_action_buttons);
        //设置总播放页数
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.fragment_container,new FragmentPlayListCount()).commit();

        //点击事件的textView

        tvBtnAllPlayList = (TextView) findViewById(R.id.tv_alllist);
        tvBtnAllPlayLists = (TextView) findViewById(R.id.tv_alllists);
        tvBtnDownLoad = (TextView) findViewById(R.id.tv_downLoade);
        //排序
        ivSort = (ImageView) findViewById(R.id.iv_sorts2);
        //浮动框停留效果
        pullZoomView = (PullZoomView) findViewById(R.id.pzv);

        llroot = (RelativeLayout) findViewById(R.id.ll_root);

        rlTop = (RelativeLayout) findViewById(R.id.tv_middle_button2);

        rlMiddle = (RelativeLayout) findViewById(R.id.tv_middle_button);

        //获取到头布局的高度
        inHeader = findViewById(R.id.in_header);

        //猜测在xml中设置效果更佳
     //   rlTop.setVisibility(View.GONE);


        rlTop.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Log.e("rltop top"," = "+rlTop.getTop());
                if (pzv.getScrollY()==0){
                    if (rlTop.getVisibility()==View.VISIBLE){

                        rlTop.setVisibility(View.GONE);
                    }
                }
            }
        });


        headerParams = (ViewGroup.MarginLayoutParams)inHeader.getLayoutParams();

        llroot.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                pzv.setOnScrollListener(new OnScrollListener() {
                   @Override
                    public void onScroll(int l, int t, int oldl, int oldt) {

                        /* if(pzv.getScrollY()>900){
                       rlTop.setVisibility(View.VISIBLE);
*/
                              LogUtil.e("改变后的高度+" + headerParams.height);
                              if (pzv.getScrollY()>0){

                                  if(rlTop.getVisibility()==View.GONE){

                                      rlTop.setVisibility(View.VISIBLE);
                                  }
                                  int mBuyLayout2ParentTop = Math.max(pzv.getScrollY(), rlMiddle.getTop());
                                  rlTop.layout(0, mBuyLayout2ParentTop, rlTop.getWidth(), mBuyLayout2ParentTop + rlTop.getHeight());

                                  LogUtil.e("改变后的高度+" + rlMiddle.getTop()+" scrolly = "+pzv.getScrollY());
                            //  }

                              }
                                if (pzv.getScrollY()>rlMiddle.getTop()){

                                    if (tvTitle.getVisibility()!=View.GONE){

                                        tvTitle.setVisibility(View.GONE);
                                    }

                                   if (llactionbars.getVisibility()!=View.VISIBLE){

                                       llactionbars.setVisibility(View.VISIBLE);
                                   }

                                }else {



                                    if (tvTitle.getVisibility()!=View.VISIBLE){

                                        tvTitle.setVisibility(View.VISIBLE);
                                    }

                                    if (llactionbars.getVisibility()!=View.GONE){

                                        llactionbars.setVisibility(View.GONE);
                                    }


                                }



                    }
                    @Override
                    public void onHeaderScroll(int currentY, int maxY) {
                        LogUtil.e("这是咋回事啊");
                        System.out.println("onHeaderScroll   currentY:" + currentY + "  maxY:" + maxY);
                    }

                    @Override
                    public void onContentScroll(int l, int t, int oldl, int oldt) {
                        System.out.println("onContentScroll   t:" + t + "  oldt:" + oldt);
                    }
                });
            }
        });

        ivHeaderCircle = (ImageView) findViewById(R.id.iv_headercircle);
        tvMsgHeader = (TextView) findViewById(R.id.tv_msgtitle);
    }




    @Override
    protected void onResume() {
        super.onResume();

    }

    private void initEvent(){
        //设置按钮点击事件
        tvBtnDownLoad.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                FragmentManager manager = getSupportFragmentManager();
                FragmentTransaction transaction = manager.beginTransaction();
                transaction.replace(R.id.fragment_container,new FragmentPlayListCount()).commit();
            }
        });
        //设置viewPager
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                //设置滑动监听

                for (int i = 0; i < mIvDotList.size(); i++) {
                    if (position==i){
                        mIvDotList.get(i).setImageDrawable(getResources().getDrawable(R.drawable.ic_album_dot_selected));
                    }else{
                        mIvDotList.get(i).setImageDrawable(getResources().getDrawable(R.drawable.ic_album_dot_unselected));
                    }

                }


            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        //回退事件
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        ivSort.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (isAes){

                    Comparator<PlayList2Data.ContentListBean.DataListBean> ascComparator = new PullListViewActivity2.PlayListCompartor();
                    //排序后的集合
                    //利用Collections类静态工具方法对集合dataList进行排序
                    //降序
                    Comparator<PlayList2Data.ContentListBean.DataListBean>desComparator = Collections.reverseOrder(ascComparator);
                    Collections.sort(dataList,desComparator);
                    //在这里post通知fragment数据已经改变
                    EventBus.getDefault().post(new PlayListEvent());
                    isAes = false;

                }else {

                    Comparator<PlayList2Data.ContentListBean.DataListBean> ascComparator = new PullListViewActivity2.PlayListCompartor();
                    //排序后的集合
                    //利用Collections类静态工具方法对集合dataList进行排序
                    //升序
                    Collections.sort(dataList,ascComparator);
                    isAes = true;
                }



                //在这里post通知fragment数据已经改变

                EventBus.getDefault().post(new PlayList2Event());
            }
        });

        pullZoomView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
       return false;
            }
        });

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initData() {

        Intent intent = getIntent();
        String needAddId = intent.getStringExtra("urlID");
        HomeUtils.getDownLoadList(new DuotinTask.IRequestCallback() {
            @Override
            public void success(Object object) {
                //将GBK格式转换为unicode
                String orignData = Unicode2CN.unicode2GBK(object.toString());
                try {
                    JSONObject root = new JSONObject(orignData);
                    String message = root.getString("error_msg");
                    if ("SUCCESS".equals(message)) {
                        final JSONObject data = root.getJSONObject("data");
                        //获取到整个的json格式数据
                        final PlayList2Data playList = PlayList2Data.objectFromData(data.toString());
                        //设置背景图片
                        String imgBurl = playList.getAlbum().getImage_url();
                        setBackgroundPicture(imgBurl);
                        //设置内容
                        final HomeMyPagerAdapter2 vpAdapter = new HomeMyPagerAdapter2(PullListViewActivity2.this,playList);
                        viewPager.setAdapter(vpAdapter);

                        //设置播放页面的数据
                        dataList = playList.getContent_list().getData_list();
                        tvBtnAllPlayList.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Toast.makeText(PullListViewActivity2.this, "点击了那个", Toast.LENGTH_SHORT).show();
                                FragmentManager manager = getSupportFragmentManager();
                                FragmentTransaction transaction = manager.beginTransaction();
                                transaction.replace(R.id.fragment_container,new FragmentPlayList2(dataList)).commit();
                            }
                        });
                        tvBtnAllPlayLists.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Toast.makeText(PullListViewActivity2.this, "点击了那个", Toast.LENGTH_SHORT).show();
                                FragmentManager manager = getSupportFragmentManager();
                                FragmentTransaction transaction = manager.beginTransaction();
                                transaction.replace(R.id.fragment_container,new FragmentPlayList2(dataList)).commit();
                            }
                        });


                        //标题栏文字
                        tvTitle.setText(playList.getAlbum().getTitle());

                        //个人信息
                        ImageLoader.getInstance().displayImage(playList.getPodcast().getImage_url(),ivHeaderCircle, ImageUtil.getCircleOptions());
                        tvMsgHeader.setText(playList.getPodcast().getReal_name());
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void error(String msg) {

            }
        },needAddId);



    }

    //这里是按降序排列
    public class PlayListCompartor implements Comparator<PlayList2Data.ContentListBean.DataListBean>{

        @Override
        public int compare(PlayList2Data.ContentListBean.DataListBean lhs, PlayList2Data.ContentListBean.DataListBean rhs) {
            return lhs.getPlay_num()-rhs.getPlay_num();
        }
    }

    }


